package ar.com.altaagenda.utils;

import java.io.InputStreamReader;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.ContentEncodingHttpClient;
import org.apache.http.params.HttpProtocolParams;

public class HttpExecutor {

	HttpClient client;
	String charset;
	
	public HttpExecutor(String charset){
		this.client = new ContentEncodingHttpClient();
		this.charset = charset;
		HttpProtocolParams.setUserAgent(client.getParams(), "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
	}
	
	public String execute(String url) throws Exception {
		//TODO fix this. Tiene que haber una manera mas elegante de resolver esto modificando el ContentEncodingHttpClient.
		InputStreamReader ir = new InputStreamReader(this.client.execute(new HttpGet(this.healUrl(url))).getEntity().getContent(), this.charset);
		StringBuffer result = new StringBuffer();
		char[] buffer = new char[1024];
		
		while(ir.read(buffer)>0){
			result.append(buffer);
		}
		return result.toString();
	}
	
	private String healUrl(String url){
		return url.replaceAll("\\\\", "");
	}
}